<?php

class Db_Record extends Base_Abstract {
	const EVENT_NEW = "new";
	const EVENT_UPDATE = "update";

	private $event = "new";
	private $_modelName;
	public $relations = array();
	public $columns = array();
	/**
	 * @var string Имя таблицы
	 */
	public $table_name = "";

	public function __construct ($event = "new", $modelName = __CLASS__) {
		$this->_modelName = $modelName;
		$this->event = $event;
		$this->setup();
	}

	public function setup (){}

	public function hasColumn ($name, $type = "varchar", $lenght = "250", array $data = array()) {
		$column = new DB_Column($name, $type, $lenght, $data);
		$this->addColumn($column);
	}

	public function addColumn (Db_Column $column) {
		$this->columns[$column->name] = $column;
	}
	
	public function hasOne($name, array $data){
		$relation = new Db_Relation_One($data);
		$this->addRelation($relation);
	}
	
	public function hasMany($name, array $data){
		$relation = new Db_Relation_Many($name, $data);
		$this->addRelation($relation);
	}

	public function addRelation(Db_Relation $relation){
		$this->relations[empty($relation->alias) ? $relation->name : $relation->alias] = $relation;
	}
	
	public function fromArray(array $array){
		foreach($array as $k => $v){
			$this->columns[$k]->value = $v;
		}
		return $this;
	}

	public function find($params = array()){
		$q = new Db_Query();
		$q->from($this->table_name);
		$q->limit(array(1));
		
		
		$q = $q->exec();
		
		return $q;
	}
	
	public function findAll($params = array()){
		$q = new Db_Query();
		$q->from($this->table_name);
		foreach($params as $p => $v){
			$q->$p($v);
		}
		
		$q = $q->collection($this->_modelName);
		
		return $q;
	}

	public function __get ($name) {
		return $this->columns[$name]->value;
	}

	public function __set ($name, $value = false) {
		$this->columns[$name]->value = $value;
	}

	public function offsetGet ($offset) {
		return $this->columns[$offset]->value;
	}

	public function offsetSet ($offset, $value) {
		$this->columns[$offset]->value = $value;
	}

}